#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
群组服务
"""

from dao.group_dao import GroupDAO
from utils.R import R
from settings import get_logger

class GroupService:
    """
    群组服务
    处理群组相关的业务逻辑
    """
    
    def __init__(self):
        self.group_dao = GroupDAO()
        self.logger = get_logger(__name__)
        
    def get_groups_by_account(self, account, page=None, per_page=None):
        """
        根据账号获取群组列表
        
        Args:
            account: 微信账号
            page: 页码，从1开始（可选，如果提供则启用分页）
            per_page: 每页记录数（可选，默认为20）
            
        Returns:
            ApiResponse: 包含群组列表的响应
        """
        try:
            # 判断是否需要分页
            if page is not None:
                # 使用分页查询
                from utils.pagination.paginator import paginate_query
                
                # 获取查询对象
                query = self.group_dao.get_groups_by_account_paginated(account)
                
                # 应用分页
                paginator = paginate_query(query, page=page, per_page=per_page or 20, order_by='id desc')
                
                # 转换为字典格式
                groups_data = []
                for group in paginator.items:
                    group_dict = {
                        'id': group.id,
                        'group_name': group.group_name,
                        'member_count': group.member_count,
                        'account': group.account
                    }
                    groups_data.append(group_dict)
                
                # 构建分页响应数据
                data = {
                    "items": groups_data,  # 使用items字段替代groups，只包含当前页数据
                    "count": paginator.total,
                    "page": paginator.page,
                    "per_page": paginator.per_page,
                    "pages": paginator.pages,
                    "has_prev": paginator.has_prev,
                    "has_next": paginator.has_next,
                    "prev_page": paginator.prev_page,
                    "next_page": paginator.next_page
                }
            else:
                # 不分页，获取所有数据
                groups = self.group_dao.get_groups_by_account(account)
                
                # 转换为字典格式
                groups_data = []
                for group in groups:
                    group_dict = {
                        'id': group.id,
                        'group_name': group.group_name,
                        'member_count': group.member_count,
                        'account': group.account
                    }
                    groups_data.append(group_dict)
                
                data = {
                    "items": groups_data,  # 使用items字段替代groups，保持字段命名一致性
                    "count": len(groups_data)
                }
                
            return R.ok(data=data)
            
        except Exception as e:
            self.logger.error(f"根据账号获取群组列表失败: {e}")
            return R.fail(message=str(e))
    
    def sync_groups_from_wechat_api(self, account):
        """
        从微信API获取群组信息并同步到数据库
        
        Args:
            account: 微信账号
            
        Returns:
            ApiResponse: 同步结果
        """
        try:
            self.logger.info(f"开始从微信API获取群组信息，账号: {account}")
            # 直接导入WechatAuto模块中的get_groups_info方法
            from utils.pywechat.pywechat.WechatAuto import get_groups_info
            self.logger.debug("调用get_groups_info方法获取群组信息")
            groups_info = get_groups_info(is_json=False)
            self.logger.debug(f"获取到群组信息: {type(groups_info)}, 数量: {len(groups_info) if groups_info else 0}")
            
            # 调用同步方法处理数据
            self.logger.info("开始同步群组信息到数据库")
            sync_result = self.sync_groups_from_wechat(account, groups_info)
            self.logger.debug(f"同步结果: {sync_result}")
            
            # 返回统一格式的响应
            self.logger.info("群聊信息同步成功")
            return R.ok(data=sync_result, message="群聊信息同步成功")
            
        except Exception as e:
            import traceback
            error_trace = traceback.format_exc()
            self.logger.error(f"从微信API同步群组信息失败: {e}\n{error_trace}")
            return R.fail(message=str(e))

    def sync_groups_from_wechat(self, account, groups_info):
        """
        从微信同步群组信息到数据库
        
        Args:
            account: 微信账号
            groups_info: 微信群组信息列表，格式为[{"群聊名称": name, "群聊人数": count}, ...]
            
        Returns:
            dict: 同步结果
        """
        try:
            self.logger.info(f"开始同步微信群组信息，账号: {account}")
            
            if not groups_info:
                self.logger.warning("微信群组信息为空")
                return {
                    "success_count": 0,
                    "failed_count": 0,
                    "total_count": 0,
                    "groups": []
                }
            
            # 准备批量处理的数据
            batch_data = []
            for group_info in groups_info:
                try:
                    group_name = group_info.get("群聊名称")
                    member_count = int(group_info.get("群聊人数", 0))
                    
                    if not group_name:
                        self.logger.warning(f"群组名称为空，跳过: {group_info}")
                        continue
                        
                    batch_data.append({
                        'account': account,
                        'group_name': group_name,
                        'member_count': member_count
                    })
                except Exception as e:
                    self.logger.error(f"处理群组数据失败: {e}, 群组信息: {group_info}")
            
            # 批量创建或更新群组
            success_groups, success_count, failed_count = self.group_dao.batch_create_or_update_groups(batch_data)
            
            # 转换为字典格式
            groups_data = []
            for group in success_groups:
                group_dict = {
                    'id': group.id,
                    'group_name': group.group_name,
                    'member_count': group.member_count,
                    'account': group.account
                }
                groups_data.append(group_dict)
            
            result = {
                "success_count": success_count,
                "failed_count": failed_count,
                "total_count": len(groups_info),
                "groups": groups_data
            }
            
            self.logger.info(f"群组同步完成，成功: {success_count}, 失败: {failed_count}")
            return result
            
        except Exception as e:
            self.logger.error(f"同步微信群组信息失败: {e}")
            raise
    
    def get_group_by_id(self, group_id):
        """
        根据ID获取群组
        
        Args:
            group_id: 群组ID
            
        Returns:
            ApiResponse: 包含群组信息的响应
        """
        try:
            group = self.group_dao.get_group_by_id(group_id)
            
            if not group:
                return R.fail(message=f"未找到ID为{group_id}的群组")
            
            # 转换为字典格式
            group_data = {
                'id': group.id,
                'group_name': group.group_name,
                'group_id': group.group_id,
                'owner_name': group.owner_name,
                'member_count': group.member_count,
                'announcement': group.announcement,
                'auto_reply_enabled': group.auto_reply_enabled,
                'reply_at_only': group.reply_at_only,
                'custom_reply_message': group.custom_reply_message,
                'welcome_enabled': group.welcome_enabled,
                'welcome_message_template': group.welcome_message_template,
                'news_push_enabled': group.news_push_enabled,
                'news_push_time': group.news_push_time,
                'is_active': group.is_active,
                'description': group.description,
                'account': group.account
            }
            
            return R.ok(data=group_data)
            
        except Exception as e:
            self.logger.error(f"根据ID获取群组失败: {e}")
            return R.fail(message=str(e))
    
    def update_group(self, group_id, data):
        """
        更新群组信息
        
        Args:
            group_id: 群组ID
            data: 更新的数据
            
        Returns:
            ApiResponse: 更新结果
        """
        try:
            group = self.group_dao.get_group_by_id(group_id)
            
            if not group:
                return R.fail(message=f"未找到ID为{group_id}的群组")
            
            # 更新群组属性
            for key, value in data.items():
                if hasattr(group, key):
                    setattr(group, key, value)
            
            # 保存更新
            self.group_dao.create_or_update_group(
                account=group.account,
                group_name=group.group_name,
                member_count=group.member_count,
                **{k: v for k, v in data.items() if hasattr(group, k)}
            )
            
            return R.ok(message="群组更新成功")
            
        except Exception as e:
            self.logger.error(f"更新群组失败: {e}")
            return R.fail(message=str(e))
    
    def delete_group(self, group_id):
        """
        删除群组
        
        Args:
            group_id: 群组ID
            
        Returns:
            ApiResponse: 删除结果
        """
        try:
            result = self.group_dao.delete_group(group_id)
            
            if result:
                return R.ok(message="群组删除成功")
            else:
                return R.fail(message=f"未找到ID为{group_id}的群组")
                
        except Exception as e:
            self.logger.error(f"删除群组失败: {e}")
            return R.fail(message=str(e))